package com.glxy.controller;

import com.alibaba.fastjson.JSON;
import com.glxy.bean.User;
import com.glxy.servlet.UserService;
import com.glxy.servlet.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.print("服务器");
        if(request.getSession().getAttribute("user") != null) {
            response.getWriter().print("success");
            return ;
        }
        request.setCharacterEncoding("utf8");

        //获取数据并转化为user对象
        String jsonStr = request.getReader().readLine();
        User user = JSON.parseObject(jsonStr, User.class);
        UserService service = new UserServiceImpl();
        //查询用户
        boolean result = service.login(user);
        response.setContentType("text/html");
        response.setCharacterEncoding("utf8");
        if(result) {
            request.getSession().setAttribute("user", user);
        }
        String message;
        if(result)
            message = "success";
        else
            message= "fail";

        response.getWriter().print(message);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
